import { useState, useEffect } from 'react'
import { BrowserRouter, useLocation, useHistory } from 'react-router-dom'
import TabsNav from './components/TabsNav/TabsNav'
import SideMenu from './components/SideMenu/SideMenu'
import { routes } from './router/routes'
import Coach from './pages/Coach/index.jsx'
import { getUserData, homeUrl } from './utils/const.ts'
import { ConfigProvider } from 'antd';
import Header from './components/Header';

function MainLayout() {
  const location = useLocation()
  const history = useHistory()
  const [tabs, setTabs] = useState([
    // {key: homeUrl, label: '教练信息', component: <Coach/>, closable: false,}
  ])
  const [activeKey, setActiveKey] = useState(homeUrl)
  // 模拟当前用户等级
  // 你可以根据实际的用户登录逻辑，从后端获取或从Context/Redux中获取
  const [currentUserLevel, setCurrentUserLevel] = useState(() => {
    const userDataString = getUserData();
    if (userDataString) {
      try {
        const userData = JSON.parse(userDataString);
        return userData.level;
      } catch (e) {
        console.error("Failed to parse user data from localStorage", e);
      }
    }
    return 1; // 默认等级为 1
  });
  const [collapsed, setCollapsed] = useState(false);

  // 菜单点击时，添加或激活标签
  const handleMenuClick = (key) => {
    console.log('routes===', routes);
    
    const route = routes.find(r => r.path === key);
    if (route) {
      // 如果不是登录页，并且标签不存在，则添加标签
      if (route.path !== '/login' && !tabs.find(tab => tab.key === key)) {
        setTabs([...tabs, { key, label: route.title, component: route.element }]);
      }
      setActiveKey(key); // <-- 激活Tab
      history.push(key); // 确保侧边菜单点击时也更新URL
    }
  };

  // 路由变化时自动添加标签
  useEffect(() => {
    console.log('Current location (in useEffect):', location.pathname);
    if (location.pathname === '/') {
      history.push(homeUrl);
      return;
    }
    const route = routes.find(r => r.path === location.pathname)
    if (route && route.path !== '/login' && !tabs.find(tab => tab.key === route.path)) {
      setTabs([...tabs, {
        label: route.title,
        key: route.path,
        component: route.element,
        closable: route.path !== homeUrl,
      }])
    }
    // 确保无论是否新增标签，都更新 activeKey
    if (route) {
      setActiveKey(route.path);
      console.log('ActiveKey set to (in useEffect):', route.path); // 使用 route.path 来记录预期的 activeKey
    }
  }, [location])

  return (
    <ConfigProvider theme={{
      token: {
        fontSize: 13,
        colorPrimary: '#146bb5',
        colorBgContainer: '#ffffff',
        colorBgLayout: '#f5f5f5',
        borderRadius: 6,
        wireframe: false,
      },
      components: {
        Layout: {
          headerBg: '#ffffff',
          siderBg: '#001529',
        },
        Menu: {
          darkItemBg: '#001529',
          darkItemSelectedBg: '#146bb5',
          darkItemHoverBg: '#1890ff',
        },
        Tabs: {
          cardBg: '#ffffff',
          cardActiveTabBg: '#1a2233',
          cardGutter: 8,
        }
      }
    }}> 
      <div className="app-container">
        {location.pathname === '/login' ? (
          routes.find(r => r.path === '/login')?.element
        ) : (
          <>
            <div className="main-layout">
              <div className="sidebar-container">
                <SideMenu
                  userLevel={currentUserLevel}
                  activeKey={activeKey}
                  onMenuClick={handleMenuClick}
                  collapsed={collapsed}
                />
              </div>
              <div className="content-container">
                <Header collapsed={collapsed} onToggle={() => setCollapsed(c => !c)} />
                <TabsNav tabs={tabs} setTabs={setTabs} activeKey={activeKey} setActiveKey={setActiveKey} />
              </div>
            </div>
          </>
        )}
      </div>
    </ConfigProvider>
  )
}

export default function App() {
  return (
    <BrowserRouter>
      <MainLayout />
    </BrowserRouter>
  )
}
